package com.ztjava.upload.cloud;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiniuSdk {
	public static String accessKey;
	public static String secretKey;
	public static String bucket;
	public static String cdn;
	
	public static String uploadToken(String key){
		Auth auth = Auth.create(accessKey, secretKey);
		return auth.uploadToken(bucket, key);
	}
	
	public static String uploadFiles(String filePath,String key){
	    Configuration cfg = new Configuration(Zone.zone0());
	    UploadManager uploadManager = new UploadManager(cfg);
	    Auth auth = Auth.create(accessKey, secretKey);
	    String upToken = auth.uploadToken(bucket);
	    try {
	    	if(key.indexOf("/")==0){
	    		key = key.substring(1,key.length());
	    	}
	        Response response = uploadManager.put(filePath, key, upToken);
	        //解析上传成功的结果
	        new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    	return null;
	    }
	    return cdn + key;
	}
}
